<?php
/**
根据文件头信息检查文件的类型，纯文本文件,如.txt文件，还有可执行文件.exe，无法检查出来
*/
class FileTypeCheckD
{
 	// 文件类型，不同的头信息
	private static $_fileFormats = Array(
  '0000002066747970' => '3gp',
  '0000001866747970' => '3gp5',
  '00004D4D585052' => 'qxd',
  'A90D000000000000' => 'dat',
  'D0CF11E0A1B11AE1' => 'doc/ppt/xls/wps',
  '1A45DFA393428288' => 'mkv',
  '1F8B08' => 'gz',
  '1FA0' => 'tar.z',
  '213C617263683E0A' => 'lib',
  '25504446' => 'pdf/fdf',
  '2A2A2A2020496E73' => 'log',
  '2E524D46' => 'rm/rmvb',
  '3026B2758E66CF11' => 'asf/wma/wmv',
  '38425053' => 'psd',
  '3C3F786D6C2076657273696F6E3D22312E30223F3E' => 'xml',
  '424C4932323351' => 'bin',
  '424D' => 'bmp/dib',
  '425A68' => 'bz2/tar.bz2/tbz2/tb2',
  '4344303031' => 'iso',
  '465753' => 'swf',
  '52494646' => 'cdr/ani/cmx/ds4/4xm/avi/cda/qcp/rmi/wav',
  '454E545259564344' => 'vcd',
  '464C56' => 'flv',
  '47494638' => 'gif',
  '4D4D002B' => 'tif/tiff',
  '494433' => 'mp3',
  '5F27A889' => 'jar',
  '4D5A' => 'dll/drv/exe/pif/qts/qtx/acm/fon/ocx/olb/scr/vbx/vxd/386',
  'EB3C902A' => 'img',
  '504B0304140000' => 'zip',
  '504B030414000600' => 'docx/pptx/xlsx',
  '526172211A0700' => 'rar',
  '664C614300000022' => 'flac',
  '89504E470D0A1A0A' => 'png',
  'AC9EBD8F0000' => 'qdf',
  'EDABEEDB' => 'rpm',
  'FFD8FF' => 'jfif/jpe/jpeg/jpg',
   '000001BA'=>'mpg',
   '000001B3'=>'mpg',
	);
 
	/**
	 * 检查文件类型
	 *
	 * @param 	string 		$filePath 	文件路径
	 * @param 	string 		$fileExt 	文件扩展名
	 *
	 * @return 	boolean
	 */
	public static function validation($filePath,$fileExt)
	{	
		//$fileExt = strrchr($filePath, ".");
		//$fileExt = $fileExt?substr($fileExt,1):$fileExt;
		// 文件格式未知
		if (!$fileExt || !isset(self::$_fileFormats[$fileExt]))
		{
			return false;
		}

		$length = strlen(self::$_fileFormats[$fileExt]);
		$bin = self::_readFile($filePath, $length);
		$fileHead = @unpack("H{$length}", $bin);
 
		// 判断文件头
		if (strtolower(self::$_fileFormats[$fileExt]) == $fileHead[1])
		{
			return true;
		}
		return false;
	}
 
	public static function getFileType($filePath)
	{
		$fileType = 'unknow';
		foreach(self::$_fileFormats as $key=>$val){
		    $length = strlen($key);
		    $bin = self::_readFile($filePath, $length);
		    $fileHead = @unpack("H{$length}", $bin);
 
		    // 判断文件头
		    if (strtolower($key) === strtolower($fileHead[1]))
		    {
			    $fileType = $val;
				break;
		    }
		}
		return $fileType;
	}

	/**
	 * 读取文件内容
	 *
	 * @param 	string 		$filePath	文件路径
	 * @param 	integer 		$size
	 *
	 * @return	string
	 */
	private static function _readFile($filePath, $size)
	{
		$file = fopen($filePath, "rb");
		$bin = fread($file, $size);
		fclose($file);
		return $bin;
	}
}

//echo FileTypeCheckD::getFileType('D:/nana.jpg');
?>